﻿using System;
using System.Collections.Generic;
using System.Text;

namespace LeetcodeTest._100._40
{
    public class Leetcode31
    {
        /*
         31. Next Permutation

             Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
             */
        public void NextPermutation(int[] nums)
        {
            if (nums.Length < 2)
                return;
            bool isChange = false;
            int tempValue;
            int lastIndex = nums.Length - 1;
            int compareIndex = lastIndex - 1;
            for (; lastIndex > 0 && compareIndex >= 0;)
            {
                if (nums[lastIndex] > nums[compareIndex])
                {
                    isChange = true;
                    tempValue = nums[lastIndex];
                    nums[lastIndex] = nums[compareIndex];
                    nums[compareIndex] = tempValue;                
                    break;
                 
                }
                else
                {
                    if (lastIndex - compareIndex == 1)
                    {
                        compareIndex--;
                        lastIndex = nums.Length - 1;
                    }
                    else
                    {
                        lastIndex--;
                    }
                }
            }
            
            if (!isChange)
            {
                //如果没有改变，则证明是数字是倒序排序，交换排序顺序
                for (int i = 0; i < nums.Length / 2; i++)
                {
                    tempValue = nums[i];
                    nums[i] = nums[nums.Length - i - 1];
                    nums[nums.Length - i - 1] = tempValue;
                }
            }
            else
            {
                //如果已经改变，则冒泡排序数据剩余部分            
                for (int i = nums.Length; i > compareIndex; i--)
                {
                    for (int j = compareIndex + 1; j < i - 1; j++)
                    {
                        if (nums[j] > nums[j + 1])
                        {
                            tempValue = nums[j];
                            nums[j] = nums[j + 1];
                            nums[j + 1] = tempValue;
                        }
                    }
                }
            }
        }
    }
}
